package com.example.ktdemo.vpgallery.utils;

import android.graphics.Bitmap;
import android.view.View;

import java.io.Serializable;

/**
 * Created by lzt
 * time 2020/10/27
 * 描述：控件工具类
 */
public class VPViewShotUtils implements Serializable {

    /**
     * 对View进行截图
     */
    public interface ViewSnapListener {
        void success(Bitmap bitmap);

        void failed(String message);
    }

    public static void viewSnapshotAndBlur(View view, ViewSnapListener listener) {
        try {
            if (view == null || !view.isAttachedToWindow()) {
                return;
            }
            //使控件可以进行缓存
            view.setDrawingCacheEnabled(true);
            //获取缓存的 Bitmap
            Bitmap drawingCache = view.getDrawingCache();
            //复制获取的 Bitmap
            drawingCache = Bitmap.createBitmap(drawingCache);
            //关闭视图的缓存
            view.setDrawingCacheEnabled(false);
            if (drawingCache == null) {
                if (listener != null) {
                    listener.failed("no cache");
                }
                return;
            }
            Bitmap finalDrawingCache = drawingCache;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final Bitmap blurBitmap = VPBlurUtils.blur(view.getContext(), 23, finalDrawingCache);
                    if (listener != null) {
                        listener.success(blurBitmap);
                    }
                }
            }).start();
        } catch (Exception e) {
            if (listener != null) {
                listener.failed(e.getMessage());
            }
        }
    }

    public static Bitmap viewSnapshot(View view) throws Exception {
        //使控件可以进行缓存
        view.setDrawingCacheEnabled(true);
        //获取缓存的 Bitmap
        Bitmap drawingCache = view.getDrawingCache();
        //复制获取的 Bitmap
        drawingCache = Bitmap.createBitmap(drawingCache);
        //关闭视图的缓存
        view.setDrawingCacheEnabled(false);
        return drawingCache;

    }


//    /**
//     * 质量压缩
//     */
//    public static Bitmap compressBitmap565(Bitmap image) {
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        image.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
//
//        BitmapFactory.Options options2 = new BitmapFactory.Options();
//        options2.inPreferredConfig = Bitmap.Config.RGB_565;
//        return BitmapFactory.decodeByteArray(outputStream.toByteArray(), 0, outputStream.toByteArray().length, options2);
//
//
////        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
////        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, null);
////        return bitmap;
//    }

}
